package com.jf3q.front.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.vo.ImgCodeVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/kaptcha")
@Tag(name = "图形验证码控制层")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha kaptcha;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/generate")
    @Operation(summary = "生成图形验证码")
    public ResultVo generate(HttpServletResponse response){
        try {
            String text = kaptcha.createText();//生成字符串
            BufferedImage image = kaptcha.createImage(text);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", out);
            byte[] captchaImage = out.toByteArray();

            out.close();

            // 使用 UUID 作为验证码的唯一标识
            String uuid = UUID.randomUUID().toString();

            // 将验证码字符串存储到 Redis 中，并设置过期时间为2分钟
            stringRedisTemplate.opsForValue().set(uuid,text,2, TimeUnit.MINUTES);


            //将字节数组和uuid直接返回给前端

           return ResultVo.success(new ImgCodeVo(uuid,captchaImage));



        } catch (IOException e) {
            throw new RuntimeException("生成图形验证码失败");
        }


    }
}
